/**
 *
 */

var Config = {
    createTagUrl:'/api/admin/dc/categories',
    selectTagUrl:'/api/admin/dc/categories',
    createUrl: '/api/admin/dc/dish',
    updateUrl: '/api/admin/dc/dish',
    deleteUrl: '/api/admin/dc/dish',
    selectUrl: '/api/admin/dc/dish',
    selectCompanyUrl:'/api/dc/list/company'
};

$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});
$.validator.addMethod('atLeastOneChecked', function (value, element) {
    var checkedCount = 0;
    $("input[name='tags']").each(function () {
        if ($(this).is(':checked')) {
            checkedCount++;
        }
    });
    return checkedCount > 0;

}, "请选择至少一项");
var input;
$("input:file").change(function(){
    input = this;
    lrz(this.files[0], {width: 640})
        .then(function (rst) {
            // 把处理的好的图片给用户看看呗
            var img = new Image();
            img.src = rst.base64;
            img.onload = function () {
                $(".dish_img").html(img);
            };
            return rst;
        })
        .then(function (rst) {
            // 这里该上传给后端啦
            // 额外添加参数
            rst.formData.append('fileLen', rst.fileLen);
            $.ajax({
                url: '/uploadForCertificate', // 这个地址做了跨域处理，可以用于实际调试
                data: rst.formData,
                enctype: 'multipart/form-data',
                processData: false,
                contentType: false,
                type: 'POST',
                dataType: 'json',
                success: function (data) {
                    if(data.type=="SUCCESS"){
                        $(".thum").val(data.msg);
                        $(input).parent().siblings("span").html("上传成功");
                        // $(input).parent("div").parent("div").next("div").html('<img src="'+data.msg+'">');
                    }else{
                        alert("上传失败，请稍后重试");
                    }
                }
            });
            return rst;
        })
        .catch(function (err) {
            alert("上传失败，请稍后重试");
        })
        .always(function () {

        });
});
$(document).ready(function () {
    $(".dish_img").html('<img src="'+$("input[id=thum]").val()+'">');
    $("input[name=price]").val(toFixedForPrice($("input[name=price]").val()));
    $.ajax(
        {
            url: Config.selectTagUrl,
            type: "GET",
            data: {companyId:$("input[id=companyId]").val(),page: 1, rows: 1000},
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var dcCategorys = [];
                dcCategorys.push('<option value="" hassubinfo="true">选择分类</option>');
                data.data.map(function (dcCategory) {
                    dcCategorys.push('<option value="');
                    dcCategorys.push(dcCategory.id);
                    dcCategorys.push('" ');
                    dcCategorys.push('hassubinfo="true">');
                    dcCategorys.push(dcCategory.name);
                    dcCategorys.push('</option>');
                });
                $("#categoryId").html(dcCategorys.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    $('#categoryId').val(categoryIdChecked);
    $(".companyId").change(function (){
        $.ajax(
            {
                url: Config.selectTagUrl,
                type: "GET",
                data: {companyId:$(this).find("option:selected").val()},
                dataType: "json",
                async: false,
                success: function (data, textStatus, jqXHR) {
                    var dcCategorys = [];
                    dcCategorys.push('<option value="" hassubinfo="true">选择分类</option>');
                    data.data.map(function (dcCategory) {
                        dcCategorys.push('<option value="');
                        dcCategorys.push(dcCategory.id);
                        dcCategorys.push('" ');
                        dcCategorys.push('hassubinfo="true">');
                        dcCategorys.push(dcCategory.name);
                        dcCategorys.push('</option>');
                    });
                    $("#categoryId").html(dcCategorys.join(''));
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
    });
    //create menu
    $('#submitForUpdate').click(function () {
            var id =$("input[id=id]").val();
            var companyId =$("input[id=companyId]").val();
            var name = $("input[name=name]").val();
            var price = Math.floor($("input[name=price]").val() * 100);
            var remark = $("input[name=remark]").val();
            var categoryId = $("#categoryId").val();
            var thum = $("input[name=thum]").val();
            $.ajax(
                {url: Config.updateUrl,
                    type: "PUT",
                    data: {id:id,companyId:companyId,name:name,price:price,remark:remark,categoryId:categoryId,thum:thum},
                    dataType: "json",
                    success: function (data, textStatus, jqXHR) {
                        toastr.success(data.msg, data.title);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        toastr.error(errorThrown, textStatus);
                    }
                });
        return false;
    });
    $('#createDishTag').click(function () {
        var name = $("input[id=tag_name]").val();
        var remark = $("input[id=tag_remark]").val();
        if ($("#companyId").val() == null || $("#companyId").val() ==""){
            alert("请选择门店")
            return;
        }else {
            var companyId =$("#companyId").val();
        }
        $.ajax(
            {url: Config.createTagUrl,
                type: "POST",
                data: {name:name,remark:remark,companyId:companyId},
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    toastr.success(data.msg, data.title);
                    $("input[id=tag_name]").val("");
                    $("input[id=tag_remark]").val("");
                    $.ajax(
                        {
                            url: Config.selectTagUrl,
                            type: "GET",
                            data: {companyId:$("#companyId").val()},
                            dataType: "json",
                            async: false,
                            success: function (data, textStatus, jqXHR) {
                                var dcCategorys = [];
                                dcCategorys.push('<option value="" hassubinfo="true">选择分类</option>');
                                data.data.map(function (dcCategory) {
                                    dcCategorys.push('<option value="');
                                    dcCategorys.push(dcCategory.id);
                                    dcCategorys.push('" ');
                                    dcCategorys.push('hassubinfo="true">');
                                    dcCategorys.push(dcCategory.name);
                                    dcCategorys.push('</option>');
                                });
                                $("#categoryId").html(dcCategorys.join(''));
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                toastr.error(errorThrown, textStatus);
                            }
                        });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
        return false;
    });
});

function fmtOper(cellvalue, options, rowObject) {
    var html = '<a class="J_menuItem" style="color:#f60;padding-right: 15px" href="/dinner_dish/' + rowObject.id + '" data-index="0">编辑</a>';
    html += "<a href='#'   style='color:#f60' onclick='Delete(" + rowObject.id + ")' >删除</a>";
    return html
}

function Delete(id) {
    updateDialog("DELETE", Config.deleteUrl + '/' + id, id);
}

function updateDialog(action, url, id) {
    $.ajax(
        {
            url: url,
            type: action,
            success: function (data, textStatus, jqXHR) {
                if (action == 'DELETE') {
                    $("#data_list").trigger("reloadGrid");
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown);
            }
        });
}